# global r1 = 0
# global r2 = 0
# global c1 = 0
# global c2 = 0

# global a1 = 1/(r1*c1)+1/(r2*c1)
# global a0 = 1/(r1*r2*c1*c2)

# function H_func(s)
#     result = a0/(s*s+a1*s+a0)
#     return result
# end

using ControlSystems
using XLSX
using CSV
using DataFrames

# 假设采样频率 fs
fs = 50  # 例如 1000 Hz
T = 1.0 / fs

r1 = 200000
r2 = 100000
c1 = 1e-6
c2 = 1e-6

a1 = 1/(r2*c1)+1/(r2*c2)
a0 = 1/(r1*r2*c1*c2)

# 定义连续时间传递函数
num = [1,0,0]
den = [1, a1, a0]
sys1 = tf(num, den)
##################

r1 = 33000
r2 = 33000
c1 = 2.2e-6
c2 = 2.2e-6

a1 = 1/(r1*c1)+1/(r2*c1)
a0 = 1/(r1*r2*c1*c2)

# 定义连续时间传递函数
num = [a0]
den = [1, a1, a0]
sys2 = tf(num, den)

sys = sys1*sys2

ssys = ss(sys)

sysd = c2d(ssys, T, :tustin)  # Tustin 方法是双线性变换

# 读取 Excel 文件中的数据
filename = "漂移测试1124_1小时.csv"  # 替换为您的文件名
data = DataFrame(CSV.File(filename))

# 提取各列数据
point_numbers = data[:, 1]
timestamps = data[:, 2]
temperatures = data[:, 3]
measurements = data[:, 4]
average_data = mean(measurements)
error_data = measurements .- average_data
origin_data = error_data
t = 0:T:(length(origin_data)-1)*T  # 时间向量
t = convert(Vector{Float64}, t)
# 模拟系统的响应
function get_origin_data(_,time)
    index = time*fs+1
    index = floor(index)
    index = convert(Int,index)
    return origin_data[index]
end

y, t, x = lsim(sysd, get_origin_data, t)
y = vec(y)
# 绘制结果
origin_data = measurements
y = y .+ average_data
using Plots
# plot(t[100:end], origin_data[100:end], label="Original Data", linewidth=2, color=:blue)
# plot!(t[100:end], y[100:end], label="Filtered Data", linewidth=2, color=:red, legend=:topright)
plot(t[10000:13100], origin_data[10000:13100], label="Original Data", linewidth=2, color=:blue)
plot!(t[10000:13100], y[10000:13100], label="Filtered Data", linewidth=2, color=:red, legend=:topright)
xlabel!("Time (s)")
ylabel!("Amplitude")
title!("Filter Response")
savefig("Active_Filter_Response.png")
println("Active_Filter_Response.png saved.")

Active_filtered_data = DataFrame(
    Point_Number=point_numbers,
    Timestamp=timestamps,
    Temperature=temperatures,
    Original_Measurement=origin_data,
    Active_Filtered=y,
)


output_filename = "Active_filtered_data.xlsx"

if isfile(output_filename)
    println("文件 $output_filename 已存在，将删除并重新保存。")
    rm(output_filename)  # 删除现有文件
else
    println("文件 $output_filename 不存在，将直接保存。")
end

XLSX.writetable(output_filename, Active_filtered_data)

println("滤波后的数据已保存到 $output_filename .xlsx")
output_filename = "Active_filtered_data.csv"

if isfile(output_filename)
    println("文件 $output_filename 已存在，将删除并重新保存。")
    rm(output_filename)  # 删除现有文件
else
    println("文件 $output_filename 不存在，将直接保存。")
end

CSV.write(output_filename, Active_filtered_data)
